<!--    系统配置 - 用户管理列表   jh -->
<template>
    <div>
        <div class="right">
            <el-row>
                <div class="ca-title pull-left"><h3 class="h3">用户管理</h3></div>
                <el-input
                    placeholder="用户名模糊查询"
                    v-model="ruleForm.name"
                    class="ca-w-280 ca-m-l-20 ca-m-r-10 pull-left"
                    @keyup.enter.native="getList"
                >
                    <el-button @click="getList" slot="append" icon="el-icon-search"></el-button>
                </el-input>
                <div class="ca-pull-right">
                    <el-button @click='showDialog'  type="primary" :disabled="!isAuthDept">
                        <img src="../../../assets/images/ca-new-dep.png" />
                        <span class="fa-span">部门管理</span>
                    </el-button>
                    <el-button icon="el-icon-plus" class="ca-color-download"  :disabled="!isAuthCreate" @click="addClient">创建用户
                    </el-button>
                </div>
            </el-row>
            <div class="ca-m-t-15" v-if="roleId === '-1'">
                <el-table
                    class="ca-table"
                    @sort-change="tableSort"
                    border
                    :data="tableData"
                    >
                    <el-table-column
                        label="序号"
                        width="80"
                        type="index" align="center">
                    </el-table-column>
                    <el-table-column
                        sortable="custom"
                        property="cnName"
                        label="用户名称" >
                        <template slot-scope="scope">
                            <el-tooltip :content="scope.row.cnName" placement="top" class="item">
                               <el-button  :disabled="!isAuthEdit"  type="text" @click="toDetail(scope.row)" class="ca-text-over-flow-ellipsis">{{ scope.row.cnName }}</el-button>
                            </el-tooltip>
                        </template>
                    </el-table-column>
                    <el-table-column
                        sortable="custom"
                        property="email"
                        label="邮箱">
                        <template slot-scope="scope">
                            <span>{{ scope.row.email }}</span>
                        </template>
                    </el-table-column>
                    <el-table-column
                        property="deptName"
                        label="部门">
                        <template slot-scope="scope">
                            <span>{{ scope.row.deptName }}</span>
                        </template>
                    </el-table-column>
                    <el-table-column
                        property="roleList2"
                        label="角色">
                        <template slot-scope="scope">
                            <span>{{scope.row.roleList2?scope.row.roleList2.substr(0,scope.row.roleList2.length-1):''}}</span>
                        </template>
                    </el-table-column>
                    <el-table-column
                        sortable="custom"
                        property="createTime"
                        label="创建时间">
                        <template slot-scope="scope">
                            <!--order="create_time"-->
                            <span>{{scope.row.createTime | moment('YYYY-MM-DD HH:mm') }}</span>
                        </template>
                    </el-table-column>
                    <el-table-column
                        sortable="custom"
                        property="lastLoginTime"
                        label="最后登录时间">
                        <template slot-scope="scope">
                           <span>{{scope.row.lastLoginTime?$moment(scope.row.lastLoginTime).format("YYYY-MM-DD HH:mm"):''}}</span>
                        </template>
                    </el-table-column>
                    <el-table-column
                        sortable="custom"
                        property="userEnable"
                        label="状态">
                        <template slot-scope="scope">
                            <!-- 1启用,2禁用-->
                            <span>{{scope.row.userEnable | getNameById('dataEnable')}}</span>
                        </template>
                    </el-table-column>
                    <el-table-column
                        property="address"
                        label="操作">
                        <template slot-scope="scope">
                            <el-button :disabled="!isAuthEable" @click="enableUser(scope.row.id,1)" v-if="scope.row.userEnable!==1" type="text">启用</el-button>
                            <el-button :disabled="!isAuthEable" @click="enableUser(scope.row.id,2)" v-if="scope.row.userEnable==1" type="text">禁用</el-button>
                            <el-button :disabled="!isAuthDel" @click="deleteClient(scope.$index,scope.row.id)" type="text">删除</el-button>
                        </template>
                    </el-table-column>
                </el-table>
                <el-pagination class="use-list-pagination"
                               @size-change="handleSizeChange"
                               @current-change="handleCurrentChange"
                               :current-page="currentPage"
                               :page-sizes="vuePageSizes"
                               :page-size="vuePageSize"
                               layout="total, sizes, prev, pager, next, jumper"
                               :total="totalCount">
                </el-pagination>
            </div>
            <div class="ca-m-t-20" v-if="roleId !== '-1'">
                <el-table
                    class="ca-table"
                    border
                    :data="tableData"
                >
                    <el-table-column
                        label="序号"
                        width="80"
                        type="index" align="center">
                    </el-table-column>
                    <el-table-column
                        property="cnName"
                        label="用户名称" >
                        <template slot-scope="scope">
                            <el-tooltip :content="scope.row.cnName" placement="top" class="item">
                                <el-button  :disabled="!isAuthEdit"  type="text" @click="toDetail(scope.row)" class="ca-text-over-flow-ellipsis">{{ scope.row.cnName }}</el-button>
                            </el-tooltip>
                        </template>
                    </el-table-column>
                    <el-table-column
                        property="email"
                        label="邮箱">
                        <template slot-scope="scope">
                            <span>{{ scope.row.email }}</span>
                        </template>
                    </el-table-column>
                    <el-table-column
                        property="deptName"
                        label="部门">
                        <template slot-scope="scope">
                            <span>{{ scope.row.deptName }}</span>
                        </template>
                    </el-table-column>
                    <!--<el-table-column-->
                        <!--property="roleList2"-->
                        <!--label="角色">-->
                        <!--<template slot-scope="scope">-->
                            <!--<span>{{scope.row.roleList2?scope.row.roleList2.substr(0,scope.row.roleList2.length-1):''}}</span>-->
                        <!--</template>-->
                    <!--</el-table-column>-->
                    <el-table-column
                        property="createTime"
                        label="创建时间">
                        <template slot-scope="scope">
                            <!--order="create_time"-->
                            <span>{{scope.row.createTime | moment('YYYY-MM-DD HH:mm') }}</span>
                        </template>
                    </el-table-column>
                    <el-table-column
                        property="lastLoginTime"
                        label="最后登录时间">
                        <template slot-scope="scope">
                            <span>{{scope.row.lastLoginTime?$moment(scope.row.lastLoginTime).format("YYYY-MM-DD HH:mm"):''}}</span>
                        </template>
                    </el-table-column>
                    <el-table-column
                        property="userEnable"
                        label="状态">
                        <template slot-scope="scope">
                            <!-- 1启用,2禁用-->
                            <span>{{scope.row.userEnable | getNameById('dataEnable')}}</span>
                        </template>
                    </el-table-column>
                    <el-table-column
                        property="address"
                        label="操作">
                        <template slot-scope="scope">
                            <el-button :disabled="!isAuthEable" @click="enableUser(scope.row.id,1)" v-if="scope.row.userEnable!==1" type="text">启用</el-button>
                            <el-button :disabled="!isAuthEable" @click="enableUser(scope.row.id,2)" v-if="scope.row.userEnable==1" type="text">禁用</el-button>
                            <el-button :disabled="!isAuthDel" @click="deleteClient(scope.$index,scope.row.id)" type="text">删除</el-button>
                        </template>
                    </el-table-column>
                </el-table>
                <div class="ca-m-t-15">
                    <el-button
                        v-if="roleId != '-1'"
                        @click="back">
                        <i class="fa fa-mail-reply ca-font-color-red"></i>
                        <span class="fa-span">返回</span>
                    </el-button>
                </div>
            </div>
        </div>
        <el-dialog
            title="部门管理"
            :visible.sync="departmentDialog"
           >
            <el-row>
                <el-col :span='16' :offset='1'>
                    <div>
                        <ul class='ca-department-ul'>
                            <li v-for="(item, index) in this.depList" :key="index" @click="selectDep(item.deptId, item.deptName, index)"><a :class="{'active':item.isActive}">{{item.deptName}}</a></li>
                        </ul>
                    </div>
                </el-col>
                <el-col :span='5' :offset='1'>
                    <el-row>
                        <el-button class="ca-dep-btn" @click="addDep()">新增</el-button>
                    </el-row>
                    <el-row class='ca-m-t-10'>
                        <el-button class="ca-dep-btn" @click="editDep()">修改</el-button>
                    </el-row>
                    <el-row class='ca-m-t-10'>
                        <el-button class="ca-dep-btn" @click="delDep()">删除</el-button>
                    </el-row>
                </el-col>
            </el-row>
            <el-row class='ca-m-t-15' v-show="showCreateDep">
                <el-col :span='16' :offset='1'>
                    <el-input v-model="newDepName" :maxlength='20'></el-input>
                </el-col>
                <el-col :span='5' :offset='1'>
                    <el-button @click="saveDep()" class="ca-dep-save-btn">保存</el-button>
                    <el-button align="right" @click="showCreateDep = false" class="ca-dep-cancel-btn">取消</el-button>
                </el-col>
            </el-row>
        </el-dialog>
    </div>
</template>

<script type="text/ecmascript-6">
    import {api} from './api';
    import {STATUS_HTTP_SUCCESS, apiHttp} from '__service/csHttp';
    import { isNoAuth } from '__service/utils';
    export default {
        data() {
            return {
                guestRelationshipAll: this.$store.state.user.dictionaryMap.guestRelationship,
                tableData: [],//后台数据
                currentPage: 1, //当前页面
                totalCount: 0,//总页数
                //权限
                isAuthSee: isNoAuth('系统配置-用户管理-查看'),
                isAuthDept: isNoAuth('系统配置-用户管理-部门管理'),
                isAuthCreate: isNoAuth('系统配置-用户管理-添加'),
                isAuthEdit: isNoAuth('系统配置-用户管理-修改'),
                isAuthDel: isNoAuth('系统配置-用户管理-删除'),
                isAuthEable: isNoAuth('系统配置-用户管理-启用/禁用'),
                ruleForm: {
                    pageIndex: 1,//查询页数
                    pageSize: this.vuePageSize,//每页数量
                    name: '',//搜索关键字
                    orderBy: 'create_time',//orderBy:为排序字段名,
                    sort: 'desc',//sort:为正序 asc 倒序 desc
                },
                // 部门列表
                depList: [],
                // 部门管理弹框开关
                departmentDialog: false,
                // 新增部门开关
                showCreateDep: false,
                // 新增部门名称
                newDepName: '',
                // 部门id
                depId: '',
                // 需要修改的部门名称
                editDepName: '',
                // 更新/删除flag  0 删除 1 更新/新增
                delStatus: null,
                roleId: this.$route.params.roleId,//当前角色id
            }
        },
        watch: {
        },
        beforeRouteEnter(to, from, next) {
            next(vm => {
                if (!vm.isAuthSee) {
                    //vm.$message.error('没有此页面的操作权限');
                    vm.$message({
                        message: '没有此页面的操作权限',
                        type: 'error',
                        center: true
                    });
                    vm.$router.go(-1);
                    return;
                }
                vm.getDepList();
                vm.getList();
                //vm.getAuth();
            });
        },
        mounted() {
        },
        methods: {
            back() {//返回到角色列表
                this.$router.push({ name: 'system-settings-role-manage'})
            },
            // 删除按钮
            delDep() {
                if (this.depId === '' || this.editDepName === '') {
                    this.$message({
                        message: '请选择需要删除的部门！',
                        type: 'warning',
                        center: true
                    });
                    return false;
                }
                this.newDepName = this.editDepName;
                this.delDepList()
            },
            //部门 删除
            delDepList() {
                //console.log(this.depId,'this.depId')
                this.$confirm('是否删除此部门?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    let param = {
                        deptId: this.depId
                    };
                    apiHttp(api.DEL_DEPT, param).then(ret => {
                        if (ret.resCode === STATUS_HTTP_SUCCESS) {
                            this.$message({
                                message: '部门删除成功！',
                                type: 'success',
                                center: true
                            });
                            this.depId = '';
                            this.newDepName = '';
                            this.editDepName = '';
                            this.getDepList()
                            this.$store.dispatch('refreshFieldList'); //更新字典
                        }
                    });
                },() => {
//                    this.$message({
//                        type: 'info',
//                        message: '已取消删除',
//                        center: true
//                    });
                })
            },
            //部门 增加/修改 接口
            editDepList() {
                //console.log(this.depId,'this.depId')
                let param = {
                    deptName: this.newDepName,
                    id: this.depId
                };
                apiHttp(api.ADD_DEPT, param).then(ret => {
                        if (ret.resCode === STATUS_HTTP_SUCCESS) {
                            if ( this.depId !== '') {
                                this.$message({
                                    message: '部门修改成功！',
                                    type: 'success',
                                    center: true
                                });
                            } else {
                                this.$message({
                                    message: '部门创建成功！',
                                    type: 'success',
                                    center: true
                                });
                            }
                            this.depId = '';
                            this.newDepName = '';
                            this.editDepName = '';
                            this.getDepList()
                            this.$store.dispatch('refreshFieldList'); //更新字典
                        }
                });
            },
            // 修改按钮
            editDep() {
                if (this.editDepName === '') {
                    this.$message({
                        message: '请选择需要修改的部门！',
                        type: 'warning',
                        center: true
                    });
                } else {
                    // 当用户先选择部门，再点新增会清除depId，再点击修改按钮时通过editDepName来找到id并赋值到depId才能修改成功
                    for (let item of this.depList) {
                        if (item.deptName === this.editDepName) {
                            this.depId = item.deptId;
                        }
                    }
                    this.newDepName = this.editDepName;
                    this.showCreateDep = true;
                }
            },
            // 选择需要修改的部门
            selectDep(id, depName, index) {
                //console.log(id, depName, index)
                this.depId = id;
                //console.log(this.depId,'this.depId')
                this.editDepName = depName;
                //  给选择的部门增加选中标识
                this.depList.map((obj, idx) => {
                    if (idx === index) {
                        obj.isActive = !obj.isActive
                    } else {
                        obj.isActive = false;
                    }
                })
            },
            // 新增按钮
            addDep() {
                this.depId = '';
                this.newDepName = '';
                this.showCreateDep = true;
            },
            // 保存按钮
            saveDep() {
                //console.log((/^\S/).test(this.newDepName))
                if ((/^\S/).test(this.newDepName)) {
                    // 判断新增部门时部门名称不能重复
                    let newArr = [];
                    for (let item of this.depList) {
                        if (item.deptName === this.newDepName) {
                            this.$message({
                                message: '该部门已存在！',
                                type: 'error',
                                center: true
                            });
                            newArr.push(this.newDepName)
                            return;
                        }
                    }
                    //如果新加的部门在原数组中不存在,添加部门
                    if (newArr.length === 0) {
                        this.editDepList();
                    }
                } else {
                    this.$message({
                        message: '部门名称不能为空！',
                        type: 'error',
                        center: true
                    });
                }
            },
            // 获取部门列表
            getDepList() {
                // 调借口
                apiHttp(api.GET_DEPT_LIST).then(ret => {
                        if (ret.resCode === STATUS_HTTP_SUCCESS) {
                            //console.log(ret,'部门列表')
                            this.depList = ret.data
                            // 给用户管理增加选中标识 isActive字段，用于样式控制
                            for (let i of this.depList) {
                                this.$set(i,'isActive',false);
                            }
                           // console.log(this.depList,"")
                        }
                    }
                );
            },
            // 部门管理弹框
            showDialog() {
                this.departmentDialog = true;
                this.showCreateDep = false;
            },
            tableSort({prop, order }) {
                if ( prop && order) {
                    //排序顺序---为正序 asc 倒序 desc
                    if (order === 'ascending') {
                        this.ruleForm.sort = 'asc'
                    } else {
                        this.ruleForm.sort = 'desc'
                    }
                    //排序字段
                    this.ruleForm.orderBy = prop.replace(/([A-Z])/g, '_$1').toLowerCase();
                    //调用列表
                    this.getList()
                }
            },
            //获取客户列表
            getList() {
                if ( this.roleId === '-1') {
                    let params = Object.assign({},this.ruleForm)
                    // console.log(params,"用户列表参数")
                    apiHttp(api.GET_USER_LIST,params).then(ret=> {
                        if (ret.resCode === STATUS_HTTP_SUCCESS) {
                            this.tableData = [...ret.data.resultData]
                            //添加一个字段
                            this.tableData.map((item)=> {
                                item.roleListOne = DuplicateRemoval(item.roleList) //数组去重
                                item.roleList2 = ''
                            })
                            //给字段赋值sub.roleName
                            this.tableData.map((item)=> {
                                item.roleListOne.map((sub)=> { //遍历去重后的数据
                                    item.roleList2 = item.roleList2 + sub.roleName + '/'
                                })
                            })
                            this.totalCount = ret.data.totalCount
                        }
                    })
                } else {
                    let params = {
                        id: this.roleId
                    }
                    // console.log(params,"用户列表参数")
                    apiHttp(api.GET_ROLE_USERLIST,params).then(ret=> {
                        if (ret.resCode === STATUS_HTTP_SUCCESS) {
                            this.tableData = [...ret.data]
                        }
                    })
                }
            },
            //pageSize 改变时会触发
            handleSizeChange(val) {
                this.ruleForm.pageSize = val
                this.getList()
            },
            //当前页改变时会触发
            handleCurrentChange(val) {
                this.ruleForm.pageIndex = val
                this.getList()
            },
            //新建项目
            addClient() {
                this.$router.push({ name: 'system-settings-user-add',params: {userId: '-1'}})
            },
            //详情页
            toDetail(row) {
                this.$router.push({ name: 'system-settings-user-add',params: {userId: row.id}})
            },
            //投资详情
            toInvestmentDetails(row) {
                this.$router.push({ name: 'client-management-investment-details',params: {eClient_bId: row.guestId,openWindow: true}})
            },
            //删除客户
            deleteClient(index,id) {
                this.$confirm('是否删除此用户信息?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    let params = {
                        id: id
                    }
                    let url = api.DELETE_USER
                    apiHttp(url,params).then(ret=> {
                        if (ret.resCode === STATUS_HTTP_SUCCESS) {
                            this.$message({
                                type: 'success',
                                message: '删除成功!',
                                center: true
                            });
                            this.tableData.splice(index, 1);
                            this.$store.dispatch('refreshFieldList'); //更新字典
                        }
                    })
                },() => {
//                    this.$message({
//                        type: 'info',
//                        message: '已取消删除',
//                        center: true
//                    });
                })
            },
            //启用/禁用用户
            enableUser(id,status) {
               // 1启用,2禁用
                this.$confirm('是否改变用户状态?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    let params = {
                        id: id,
                        status: status
                    }
                    let message = ''
                    if (status === 1) {
                        message = '启用用户成功!'
                    } else {
                        message = '禁用用户成功!'
                    }
                    apiHttp(api.ENABLE_USER,params).then(ret=> {
                        if (ret.resCode === STATUS_HTTP_SUCCESS) {
                            //console.log(ret,"启用/禁用用户")
                            this.$message({
                                type: 'success',
                                message: message,
                                center: true
                            });
                            this.getList()
                            this.$store.dispatch('refreshFieldList'); //更新字典
                        }
                    })
                },() => {
//                    this.$message({
//                        type: 'info',
//                        message: '取消操作',
//                        center: true
//                    });
                })
            },
        },
        components: {

        },
    }
    //数组去重
    function DuplicateRemoval(oldArr) {
        if (oldArr.length !== 0) {
            let allArr = [];//新数组
            for (let i = 0; i < oldArr.length; i++) {
                let flag = true;
                if (allArr.length !== 0) {
                    for (var j = 0; j < allArr.length; j++) {
                        if (oldArr[i].id === allArr[j].id) {
                            flag = false;
                        }
                    }
                }
                if (flag) {
                    allArr.push(oldArr[i]);
                }
            }
            return allArr
        } else {
            return []
        }
    }
</script>
<style rel="stylesheet/scss" lang="scss" scoped>
    /*分页样式*/
    .use-list-pagination{
        margin: 31px  25%;
    }
    .ca-department-ul {
        width: 100%;
        height: 128px;
        border: solid 1px #dbe3ea;
        overflow: auto;
        li {
            cursor: pointer;
            height: 34px;
            line-height: 34px;
        }
    }
    .ca-dep-btn {
        width: 100%;
    }
    // 选中li样式
    .ca-ul-li_bg {
        background: #378ee7;
    }
    .ca-department-ul li a{
        display: block;
        padding-left: 10px;
        text-align: left;
        color: #333;
    }
    .ca-department-ul li a:hover{
        background-color: #e7e7e7;
        cursor: pointer;
    }
    .ca-department-ul li a.active{
        background-color: #378ee7;
        color: #fff;
    }
    .ca-dep-save-btn {
        background: #378ee7;
        color: #fff;
        padding: 10px 15px;
    }
    .ca-dep-cancel-btn {
        background: #babcbf;
        color: #fff;
        padding: 10px 15px;
    }
    .ca-dep-dialog-btn {
        background: #389bef;
        border: solid 1px #378ee7;
        color: #fff;
    }

</style>
